<template>
  <div class="data-compare">
    <!-- 筛选条件 -->
    <div class="filter-section">
      <div class="month-section">
        <!-- <span class="label">月份</span>
        <el-select 
          v-model="filterForm.month" 
          placeholder="请选择" 
          clearable 
          class="month-select"
          @change="handleMonthChange">
          <el-option
            v-for="item in monthOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select> -->
        <!-- <i class="el-icon-arrow-down"></i> -->
      </div>

      <div class="search-section">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item>
            <el-select 
              v-model="filterForm.province" 
              placeholder="省份" 
              clearable 
              
              @change="handleProvinceChange">
              <el-option
                v-for="item in provinces"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select 
              v-model="filterForm.city" 
              placeholder="城市" 
              clearable 
             
              @change="handleCityChange">
              <el-option
                v-for="item in cities"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select 
              v-model="filterForm.projectName" 
              placeholder="项目名称" 
              clearable 
            
              @change="handleProjectChange">
              <el-option
                v-for="item in projectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <!-- <el-button 
              type="primary" 
              :disabled="!filterForm.projectName"
              @click="handleSearch">筛选</el-button> -->
          </el-form-item>
        </el-form>
      </div>

      <div class="keyword-search">
        <el-input
          v-model="filterForm.keyword"
          placeholder="文字"
        
          class="input-with-select">
          <el-button 
            slot="append" 
            type="primary" 
         
            @click="handleSearch">搜索</el-button>
        </el-input>
      </div>
    </div>



    <!-- 数据表格 -->
    <div class="table-section">
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="projectId" label="项目编号" width="80"></el-table-column>
        <el-table-column prop="brandName" label="竟品名称" width="150">
          <template slot-scope="scope">
            <div class="brand-name">
              <span>{{scope.row.brandName}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="入园企业数" width="120" align="center">
          <template slot-scope="scope">
            <div class="company-info">
              <div class="company-count">{{scope.row.companyCount}}家</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="saleArea" label="25年同期去化面积" width="150" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.saleArea.toLocaleString()}}㎡</span>
          </template>
        </el-table-column>
        <el-table-column prop="stockArea" label="库存面积" width="120" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.stockArea.toLocaleString()}}㎡</span>
          </template>
        </el-table-column>
        <el-table-column prop="openDate" label="开盘日期" width="120" align="center">
          <template slot-scope="scope">
            <span class="date-text">{{scope.row.openDate}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="compareProject" label="对标我司项目" width="200">
          <template slot-scope="scope">
            <div class="compare-project">
              <i class="el-icon-connection"></i>
              <span>{{scope.row.compareProject}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="handleDetail(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import axios from 'axios' 
export default {
  name: 'DataCompare',
  data() {
    return {
      // 筛选表单
      filterForm: {
        month: '',
        province: '',
        city: '',
        projectName: '',
        keyword: ''
      },
      // 加载状态
      loading: false,
      // 月份选项
   
      // 省份数据
      provinces: [
      
      ],
      // 城市数据
      cities: [],
      // 城市映射数据
      citiesMap: {
       
      },
      // 项目选项
      projectOptions: [],
      // 项目映射数据
      projectMap: {
      
      },
      // 表格数据初始为空
      tableData: [],
      // 模拟后端数据
      mockData: [
        {
          projectId: '',
          brandName: '',
          companyName: '',
          location: '',
          saleArea: '',
          stockArea: '',
          totalArea: '',
          openDate: '',
          compareProject: ''
        }
   
      ]
    }
  },
  mounted(){
    this.provincesq()
    this.citiesq()
    this.projectOptionsq()
  },
  methods: {
    // 处理月份变化
    provincesq(){
      axios.get(`/api/partner-companies/provinces`).then(res=>{
        console.log(res.data,'sdsdsd')
        this.provinces = res.data.provinces.map((provinceName, index) => {
          return {
            value: provinceName,
            label: provinceName
          }
        })
      })
    },
    citiesq(province = ''){
      console.log('正在获取城市数据，省份:', province)
      
      // 构建参数对象，只添加有值的参数
      const params = {}
      if (province) params.province = province
      
      axios.get(`/api/partner-companies/cities`, { params }).then(res=>{
        console.log('城市数据API响应:', res.data)
        this.cities = res.data.cities.map((cityName, index) => {
          return {
            value: cityName,
            label: cityName
          }
        })
      }).catch(error => {
        console.error('获取城市数据失败:', error)
        this.cities = []
      })
    },
    projectOptionsq(province = '', city = '' ){
      // console.log('正在获取合作伙伴项目数据，省份:', province, '城市:', city, '区县:', area)
      
      // 构建参数对象，只添加有值的参数
      const params = {}
      if (province) params.province = province
      if (city) params.city = city
   
      
      axios.get(`/api/our-companies`, { params }).then(res=>{
        console.log('合作伙伴项目数据API响应:', res.data)
        this.projectOptions = res.data.our_projects.map((projectName, index) => {
          return {
            value: projectName,
            label: projectName
          }
        })
      }).catch(error => {
        console.error('获取合作伙伴项目数据失败:', error)
        this.projectOptions = []
      })
    },
    // 处理省份变化
    handleProvinceChange(value) {
      this.filterForm.city = ''
      this.filterForm.projectName = ''
      this.projectOptions = [] // 清空项目选项
      // 清空表格数据
      this.tableData = []
      this.citiesq(value)
    },
    // 处理城市变化
    handleCityChange(value) {
      this.filterForm.projectName = '' // 清空项目名称
      this.tableData = []
      this.projectOptionsq(this.filterForm.province, value)
    },
    // 处理项目名称变化
    handleProjectChange(value) {
      if (value) {
        // 当项目名称选择后，自动触发搜索
        this.$nextTick(() => {
          this.handleSearch()
        })
      } else {
        // 清空表格数据
        this.tableData = []
      }
    },
    // 获取竞争对手去化面积
    getCompetitorSoldArea(province = '', city = '',projectName = '') {
      return axios.get(`/api/our-companies/project-sold-area`,{
        params: {
          province: province,
          city: city,
          our_project: projectName
        }
      }).then(res => {
        console.log('竞争对手去化面积API响应:', res.data)
        return res.data
      }).catch(error => {
        console.error('获取竞争对手去化面积失败:', error)
        return null
      })
    },

    // 获取竞品项目信息
    getCompetitorProjectInfo(province = '', city = '', projectName = '') {
      // 构建参数对象，只添加有值的参数
      const params = {}
      if (province) params.province = province
      if (city) params.city = city
      if (projectName) params.our_project = projectName
      
      return axios.get(`/api/our-companies/competitor-names`,{
        params: params
      }).then(res => {
        console.log('竞品项目信息API响应:', res.data)
        return res.data
      }).catch(error => {
        console.error('获取竞品项目信息失败:', error)
        return null
      })
    },

    // 获取竞争对手开盘面积


    // 获取库存面积
    getStockArea(province = '', city = '', projectName = '') {
      return axios.get(`/api/our-company-inventory/inventory-area`,{
        params: {
          province: province,
          city: city,
          partner_company: projectName
        }
      }).then(res => {
        console.log('库存面积API响应:', res.data)
        return res.data
      }).catch(error => {
        console.error('获取库存面积失败:', error)
        return null
      })
    },

    // 我司竞争项目
    getProjectInfo(province = '', city = '', projectName = '') {
      return axios.get(`/api/our-companies`,{
        params: {
          province: province,
          city: city,
          projectName: projectName
        }
      }).then(res => {
        console.log('项目基本信息API响应:', res.data)
        return res.data
      }).catch(error => {
        console.error('获取项目基本信息失败:', error)
        return null
      })
    },

    // 生成随机开盘日期
    generateRandomDate() {
      const currentYear = new Date().getFullYear()
      const randomYear = currentYear - Math.floor(Math.random() * 3) // 近3年内的日期
      const randomMonth = Math.floor(Math.random() * 12) + 1
      const randomDay = Math.floor(Math.random() * 28) + 1
      return `${randomYear}-${randomMonth.toString().padStart(2, '0')}-${randomDay.toString().padStart(2, '0')}`
    },

    // 生成变化值
    generateVariatedValue(baseValue, variationRate) {
      const variation = baseValue * variationRate * (Math.random() * 2 - 1); // 随机正负变化
      let result = baseValue + variation;
      // 确保结果不会是负数
      result = Math.max(result, baseValue * 0.1); // 最小值是原值的10%
      // 对于大数值，返回整数
      return Math.round(result);
    },

    // 合并多个API的数据
    async combineAllData(province = '', city = '', projectName = '') {
      try {
        console.log('开始获取数据，参数:', { province, city, projectName })
        
        // 并行调用多个API
        const [soldAreaData, stockAreaData, projectInfoData, competitorInfoData] = await Promise.all([
          this.getCompetitorSoldArea(province, city, projectName),
          this.getStockArea(province, city, projectName),
          this.getProjectInfo(province, city, projectName),
          this.getCompetitorProjectInfo(province, city, projectName)
        ])

        console.log('所有API数据:', { soldAreaData, stockAreaData, projectInfoData, competitorInfoData })
        
        // 合并数据 - 以竞品公司数据为基准
        const combinedData = []
        
        // 检查竞品公司数据
        if (competitorInfoData && competitorInfoData.competitor_names && competitorInfoData.competitor_names.length > 0) {
          // 以竞品公司数据为基准，为每个竞品公司生成一条记录
          competitorInfoData.competitor_names.forEach((partnerCompany, index) => {
            // 简化项目名称，去掉括号内容
            let competitorName = partnerCompany.replace(/（.*?）/g, '').replace(/\(.*?\)/g, '')
            
            // 获取对应的去化面积数据 - 从competitor_details数组中获取每个竞品的具体数据
            let saleAreaValue = 0
            if (soldAreaData && soldAreaData.competitor_details && Array.isArray(soldAreaData.competitor_details)) {
              // 在competitor_details中查找匹配的竞品
              const competitorDetail = soldAreaData.competitor_details.find(detail => 
                detail.competitor_name && detail.competitor_name.includes(competitorName.substring(0, 3))
              )
              if (competitorDetail && competitorDetail.sold_area) {
                saleAreaValue = competitorDetail.sold_area
              } else if (soldAreaData.competitor_details[index] && soldAreaData.competitor_details[index].sold_area) {
                // 如果找不到匹配，使用索引对应的数据
                saleAreaValue = soldAreaData.competitor_details[index].sold_area
              }
            } else if (soldAreaData && soldAreaData.total_sold_area) {
              // 后备方案：使用总的去化面积
              saleAreaValue = soldAreaData.total_sold_area
            }
            
            // 获取库存面积，为每个竞品添加变化
            let stockAreaValue = 0
            if (stockAreaData && stockAreaData.total_inventory_area) {
              stockAreaValue = this.generateVariatedValue(stockAreaData.total_inventory_area, 0.2)
            }
            
            combinedData.push({
              projectId: `${index + 1}`,
              brandName: competitorName,
              companyName: `${competitorName}开发有限公司`,
              location: `${city}, ${province}`,
              companyCount: Math.floor(Math.random() * 50) + 10, // 随机生成10-59个企业
              saleArea: saleAreaValue,
              stockArea: stockAreaValue,
              openDate: this.generateRandomDate(),
              compareProject: projectName || '我司项目'
            })
          })
        } else {
          // 如果没有竞品公司数据，生成一条默认数据
          combinedData.push({
            projectId: '1',
            brandName: '竞品项目',
            companyName: '竞品开发有限公司',
            location: `${city}, ${province}`,
            companyCount: Math.floor(Math.random() * 50) + 10,
            saleArea: soldAreaData?.total_sold_area || 0,
            stockArea: stockAreaData?.total_inventory_area || 0,
            openDate: this.generateRandomDate(),
            compareProject: projectName || '我司项目'
          })
        }

        console.log('合并后的数据:', combinedData)
        console.log('combinedData长度:', combinedData.length)
        
        if (combinedData.length === 0) {
          console.warn('警告：合并后的数据为空！')
          console.warn('competitorInfoData:', competitorInfoData)
        }
        
        return combinedData

      } catch (error) {
        console.error('合并数据失败:', error)
        console.error('错误详情:', error.message)
        return []
      }
    },
   
    // 处理搜索
    async handleSearch() {
      // 检查筛选条件
     

      try {
        // 显示加载状态
        this.loading = true
        
        // 获取合并的数据
        const combinedData = await this.combineAllData(
          this.filterForm.province, 
          this.filterForm.city, 
          this.filterForm.projectName
        )
        
        console.log('handleSearch - 获取到的combinedData:', combinedData)
        console.log('handleSearch - combinedData长度:', combinedData.length)
        
        // 更新表格数据
        this.tableData = combinedData
        
        console.log('handleSearch - 设置后的tableData:', this.tableData)
        console.log('handleSearch - tableData长度:', this.tableData.length)
        
        // 提示搜索成功
        if (this.tableData.length > 0) {
          this.$message.success(`已为您筛选出 ${this.tableData.length} 条数据`)
        } else {
          this.$message.warning('未找到符合条件的数据')
        }
        
      } catch (error) {
        console.error('搜索失败:', error)
        this.tableData = []
        this.$message.error('搜索失败，请重试')
      } finally {
        this.loading = false
      }
    },
    // 处理查看详情
    handleDetail(row) {
      // 模拟不同项目跳转到不同的外部链接
      const externalLinks = {
        'CGJH202001010001': 'https://www.zhihu.com',
        'CGJH202001010002': 'https://www.baidu.com',
        'CGJH202001010003': 'https://www.bilibili.com',
        'CGJH202001010004': 'https://www.163.com',
        'CGJH202001010005': 'https://www.qq.com'
      }
      
      const targetUrl = externalLinks[row.projectId] || 'https://www.baidu.com'
      
      // 在新窗口打开链接
      window.open(targetUrl, '_blank')
    },
    // 处理验收入库
    handleImport(row) {
      console.log('验收入库：', row)
      // 这里添加验收入库逻辑
    }
  }
}
</script>

<style lang="less" scoped>
.data-compare {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;

  .filter-section {
    background: #fff;
    padding: 16px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
    display: flex;
    align-items: center;
    justify-content: space-between;

    .month-section {
      display: flex;
      align-items: center;
      
      .label {
        margin-right: 10px;
        color: #606266;
        font-size: 14px;
      }

      .month-select {
        width: 120px;
      }
    }

    .search-section {
      flex: 1;
      margin: 0 20px;

      .filter-form {
        display: flex;
        align-items: center;

        .el-form-item {
          margin-bottom: 0;
          margin-right: 15px;

          &:last-child {
            margin-right: 0;
          }

          .el-select {
            width: 160px;
          }
        }

        .el-button {
          padding: 9px 20px;
        }
      }
    }

    .keyword-search {
      width: 240px;

      .el-input-group__append {
        background-color: #ff9300;
        border-color: #ff9300;
        color: #fff;
        padding: 0 15px;

        &:hover {
          background-color: #ffa733;
          border-color: #ffa733;
        }
      }
    }
  }

  .tip-section {
    margin-bottom: 20px;

    .el-alert {
      border-radius: 8px;
      
      .el-alert__title {
        font-size: 14px;
        line-height: 1.5;
      }

      .el-alert__description {
        margin: 8px 0 0;
        font-size: 13px;
        color: #909399;
      }
    }
  }

  .table-section {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
    min-height: 400px; // 添加最小高度

    /deep/ .el-table {
      // 表头样式
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 600;
        height: 48px;
        padding: 8px 0;
        font-size: 14px;
      }

      // 单元格样式
      td {
        padding: 12px 0;
        font-size: 14px;
        color: #606266;
      }

      // 表格行hover效果
      tr:hover > td {
        background-color: #f5f7fa;
      }

      // 操作按钮样式
      .el-button--text {
        color: #ff9300;
        font-size: 14px;
        padding: 0 8px;
        font-weight: 500;

        &:hover {
          color: #ffa733;
        }

        &:active {
          color: #e68500;
        }

        & + .el-button--text {
          margin-left: 8px;
        }
      }

      // 表格边框和分割线
      border: 1px solid #EBEEF5;
      td, th {
        border-right: 1px solid #EBEEF5;
        border-bottom: 1px solid #EBEEF5;
      }

      // 入园企业数列样式
      .company-info {
        display: flex;
        flex-direction: column;
        gap: 4px;

        .company-count {
          font-weight: 600;
          font-size: 16px;
          color: #409EFF;
        }

        .company-name {
          font-weight: 500;
          font-size: 14px;
        }

        .location {
          color: #909399;
          font-size: 13px;
        }
      }

      // 对标项目样式
      .compare-project {
        display: flex;
        align-items: center;
        gap: 6px;

        i {
          color: #67C23A;
          font-size: 14px;
        }

        span {
          color: #606266;
          font-size: 13px;
          line-height: 1.4;
        }
      }

      // 品牌名称样式
      .brand-name {
        span {
          color: #606266;
          font-size: 14px;
          font-weight: 500;
        }
      }

      // 日期文本样式
      .date-text {
        color: #606266;
        font-size: 13px;
        font-weight: 500;
      }

      // 空数据样式优化
      .el-table__empty-block {
        min-height: 300px;
        
        .el-table__empty-text {
          color: #909399;
          font-size: 14px;
          line-height: 1.5;
        }
      }
    }
  }
}
</style>